package com.example.Impl;

import com.example.entity.FlightInfo;
import com.example.service.FlightService;
import org.apache.dubbo.config.annotation.DubboService;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import java.util.ArrayList;
import java.util.List;

@DubboService
public class FlightServiceImpl implements FlightService {

    @Override
    public List<FlightInfo> queryByCondition(String from, String to, String departureDate, String before) {
        System.out.println(2);
        List<FlightInfo> result = new ArrayList<>();
        try {
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc = builder.parse(getClass().getClassLoader().getResourceAsStream("flights.xml"));
            XPath xpath = XPathFactory.newInstance().newXPath();
            System.out.println(3);

            // 构建 XPath 只查 from 和 to，departureTime 在 Java 中处理
            StringBuilder exprBuilder = new StringBuilder("//flight[");

            if (from != null && !from.isEmpty()) {
                exprBuilder.append("normalize-space(from)='").append(from).append("' and ");
            }
            if (to != null && !to.isEmpty()) {
                exprBuilder.append("normalize-space(to)='").append(to).append("' and ");
            }
            if (departureDate != null && !departureDate.isEmpty()) {
                exprBuilder.append("normalize-space(departureDate)='").append(departureDate).append("' and ");
            }
            if (exprBuilder.toString().endsWith(" and ")) {
                exprBuilder.setLength(exprBuilder.length() - 5); // 移除最后的 " and "
            } else {
                exprBuilder.append("true()"); // 无条件默认 true()
            }
            exprBuilder.append("]");

            String expr = exprBuilder.toString();
            System.out.println("XPath Expression: " + expr);

            NodeList nodes = (NodeList) xpath.evaluate(expr, doc, XPathConstants.NODESET);
            System.out.println("匹配航班数量：" + nodes.getLength());

            for (int i = 0; i < nodes.getLength(); i++) {
                Element flight = (Element) nodes.item(i);
                String departureTime = flight.getElementsByTagName("departureTime").item(0).getTextContent().trim();

                // departureTime compare (注意格式必须是 HH:mm)
                if(before.isEmpty()) {
                    System.out.println(5);
                }
                if (before.isEmpty() || departureTime.compareTo(before) < 0) {
                    FlightInfo info = new FlightInfo(
                            flight.getElementsByTagName("number").item(0).getTextContent().trim(),
                            flight.getElementsByTagName("from").item(0).getTextContent().trim(),
                            flight.getElementsByTagName("to").item(0).getTextContent().trim(),
                            flight.getElementsByTagName("departureDate").item(0).getTextContent().trim(),
                            departureTime,
                            flight.getElementsByTagName("arrivalDate").item(0).getTextContent().trim(),
                            flight.getElementsByTagName("arrivalTime").item(0).getTextContent().trim(),
                            flight.getElementsByTagName("status").item(0).getTextContent().trim()
                    );
                    result.add(info);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 打印结果
        for (FlightInfo info : result) {
            System.out.println(info);
        }
        return result;
    }


}
